# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Contributor: omni <omni+alpine@hack.org>
# Maintainer: Celeste <cielesti@protonmail.com>
maintainer="Celeste <cielesti@protonmail.com>"
pkgname=dune
pkgver=3.16.1
pkgrel=0
pkgdesc="A composable build system for OCaml (formerly Jbuilder)"
url="https://dune.build/"
arch="all"
license="MIT"
checkdepends="bash"
makedepends="ocaml"
provides="jbuilder=$pkgver-r$pkgrel"
subpackages="$pkgname-doc $pkgname-emacs::noarch"
source="$pkgname-$pkgver.tar.gz::https://github.com/ocaml/dune/archive/$pkgver.tar.gz"
options="!check"  # FIXME requires ocaml-menhir

# When enabling dune-configurator for riscv64,
# create an OCaml 5 variant of ocaml4-abuild-find.
_configurator="dune-configurator"

case "$CARCH" in
	arm*|x86) options="$options textrels" ;;
	riscv64|loongarch64)
		_configurator=""
		makedepends="${makedepends//ocaml/ocaml5}"
		;;
esac

subpackages="$subpackages $_configurator"

prepare() {
	default_prepare

	# This allows 'dune --version' to output the correct version instead of "n/a"
	sed -i "/^(name dune)/a (version $pkgver)" dune-project
	# This enables dune-configurator to use the vendored csexp module
	sed -i 's/stdune.csexp/dune-configurator.csexp/' vendor/csexp/src/dune
}

build() {
	./configure --libdir="$(ocamlc -where)" \
		--bindir="/usr/bin" --sbindir="/usr/sbin" --etcdir="/etc" \
		--mandir="/usr/share/man" --docdir="/usr/share/doc" \
		--datadir="/usr/share"

	ocaml boot/bootstrap.ml --verbose
	./dune.exe build \
		-p dune,dune-configurator \
		--profile dune-bootstrap --verbose
}

check() {
	./dune.exe runtest --verbose
}

package() {
	./dune.exe install \
		--destdir="$pkgdir" \
		dune $_configurator

	# Duplicate of usr/share/doc/dune
	rm -Rf "$pkgdir"/usr/share/doc/dune-configurator
}

emacs() {
	depends="$pkgname"
	install_if="$pkgname=$pkgver-r$pkgrel emacs"
	pkgdesc="Emacs plugins for $pkgname"

	amove usr/share/emacs
}

configurator() {
	pkgdesc="System config helper for the Dune OCaml build system"
	provides="$subpkgname-dev=$pkgver-r$pkgrel"

	amove usr/lib/ocaml/"$subpkgname"
}

prepare_py_provides() {
	local datadir="${subpkgdir:-$pkgdir}"
	local pkgbasedir=${pkgbasedir:-"$startdir/pkg"}
	local controldir="$pkgbasedir"/.control.${subpkgname:-$pkgname}

	makedepends_has "ocaml5" && return 0
	options_has "!tracedeps" && return 0

	ocaml4-abuild-find provides \
		"$datadir"/usr/lib/ocaml \
		"$controldir" \
		"$pkgver-r$pkgrel"
}

scan_python3_dependency() {
	local controldir="$2" datadir="$3"

	makedepends_has "ocaml5" && return 0

	ocaml4-abuild-find requires \
		"$datadir"/usr/lib/ocaml \
		"$controldir"
}

sha512sums="
18e8022c5fa276e06f788cf25a4d6d08e3247c546cd69a5206d4e78ece1f47a615c6d5842e68e1fa7908cae7ae8c6e4f31d2eb835d97b5e6b5e4154957139e9f  dune-3.16.1.tar.gz
"
